package org.csu.mypetstore.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.csu.mypetstore.domain.AlipayTransaction;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.AlipayTransactionService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

//@RestController
@Controller
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    OrderService orderService;
    @Autowired
    AlipayTransactionService transactionService;

    private final String APP_ID = "这里改成你的APP ID";
    private final String APP_PRIVATE_KEY = "这里改成你的private key";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "这里改成你的public key";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://公网地址/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/alipay/returnUrl";

    @RequestMapping("/paytest")
    public void alipay( HttpServletResponse httpResponse ) throws IOException {

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient( GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE );
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl( RETURN_URL );
        request.setNotifyUrl( NOTIFY_URL );

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        System.out.println(out_trade_no);
        //付款金额，必填
//        String total_amount = Integer.toString(1);
        String total_amount = Double.toString( 0.01 );
        //订单名称，必填
        String subject = "test";
        //商品描述，可空
        String body = "测试商品";
        request.setBizContent( "{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}" );
        String form = "";
        try {
            form = alipayClient.pageExecute( request ).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType( "text/html;charset=" + CHARSET );
        httpResponse.getWriter().write( form );// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping("/payorder")
    public void alipayForOrder( HttpServletResponse httpResponse, String orderId ) throws IOException {

        Order order = orderService.getOrder( Integer.parseInt( orderId ) );
        BigDecimal totalPrice = order.getTotalPrice().setScale( 2 );

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient( GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE );
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl( RETURN_URL );
        request.setNotifyUrl( NOTIFY_URL );

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        order.setAlipayOutTradeNo( out_trade_no );
        orderService.updateOrder( order );
        //付款金额，必填
        String total_amount = totalPrice.toPlainString();
        //订单名称，必填
        String subject = "JPetStore Payment";
        //商品描述，可空
        String body = "OrderID: " + orderId;
        request.setBizContent( "{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}" );
        String form = "";
        try {
            form = alipayClient.pageExecute( request ).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType( "text/html;charset=" + CHARSET );
        httpResponse.getWriter().write( form );// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @GetMapping(value = "/returnUrl")
    public String returnUrl( HttpServletRequest request, HttpServletResponse response )
            throws IOException, AlipayApiException {
        System.out.println( "=================================同步回调=====================================" );

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for ( Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get( name );
            String valueStr = "";
            for ( int i = 0; i < values.length; i++ ) {
                valueStr = ( i == values.length - 1 ) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 对乱码进行处理
            valueStr = new String( valueStr.getBytes( "utf-8" ), "utf-8" );
            params.put( name, valueStr );
        }

        System.out.println( params );//查看参数都有哪些
        // 商户订单号
        String out_trade_no = new String( request.getParameter( "out_trade_no" ).getBytes( "ISO-8859-1" ), "UTF-8" );
        // 支付宝交易号
        String trade_no = new String( request.getParameter( "trade_no" ).getBytes( "ISO-8859-1" ), "UTF-8" );
        //新建交易对象
        AlipayTransaction transaction = new AlipayTransaction();
        transaction.setOutTradeNo( out_trade_no );
        transaction.setAlipayTradeNo( trade_no );

        boolean signVerified = AlipaySignature.rsaCheckV1( params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE ); // 调用SDK验证签名
        //验证签名通过
        if ( signVerified ) {
            // 付款金额
            String total_amount = new String( request.getParameter( "total_amount" ).getBytes( "ISO-8859-1" ), "UTF-8" );

            //插入交易对象表
            transaction.setPaymentStatus( true );
            transactionService.insertTransaction( transaction );

            //更新订单状态
            Order order = orderService.getOrderByOutTradeNo( out_trade_no );
            order.setStatus( Order.STATUS_AWAITING );
            orderService.updateOrder( order );
            orderService.updateOrderStatus( order );

            System.out.println( "商户订单号=" + out_trade_no );
            System.out.println( "支付宝交易号=" + trade_no );
            System.out.println( "付款金额=" + total_amount );

            return "alipay/success";//跳转付款成功页面
        } else {
            //插入交易对象表
            transaction.setPaymentStatus( false );
            transactionService.insertTransaction( transaction );

            return "catalog/main";//跳转付款失败页面
        }

    }

}



